package com.cmfi.service.impl.userRoleAuthImpl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmfi.SpringbootApplication;
import com.cmfi.dao.userRoleAuthDao.RoleDao;
import com.cmfi.dao.userRoleAuthDao.UserDao;
import com.cmfi.dao.userRoleAuthDao.UserRoleDao;
import com.cmfi.domain.userRoleAuthEntity.LoginUser;
import com.cmfi.domain.userRoleAuthEntity.Role;
import com.cmfi.domain.userRoleAuthEntity.User;
import com.cmfi.domain.userRoleAuthEntity.UserAndRole;
import com.cmfi.domain.userRoleAuthEntity.UserRoleAndAuth;
import com.cmfi.service.inter.userRoleAuthInter.UserService;
import com.cmfi.utils.Cache;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDao userDao;
	
	@Autowired
	private RoleDao roleDao;
	
    @Autowired
    private Cache cache;
	
	@Autowired
	private UserRoleDao userRoleDao;
	
	@Autowired
	private PasswordEncoder encode;
	static Logger logger = LoggerFactory.getLogger(SpringbootApplication.class);

	@Override
	public boolean saveUser(User user) throws Exception {
		User userFromDao = userDao.getFirstByUsername(user.getUsername());
		if (userFromDao != null) {
			throw new Exception("用户名已存在");
		}
		String pass = encode.encode(user.getPassword());
		logger.info("[UserServiceImpl][saveUser]  pass:{}", pass);
		user.setPassword(pass);
		userDao.saveUser(user);
		return false;
	}

	@Override
	public void updatePassword(Long id, User user) throws Exception {
		User userFromDao = userDao.getUserByUserId(id);
		String pass = userDao.getPasswordByUserId(id);
		if (userFromDao == null) {
			throw new Exception("用户不存在");
		}
		String password = encode.encode(pass);
		logger.info("[UserServiceImpl][updatePassword] password:{}", password);
		user.setId(id);
		user.setPassword(password);
		userDao.updateUserPass(user);
	}

	@Override
	public boolean authorizeRoleForUser(Long userId, Long roleId) throws Exception {
		// TODO Auto-generated method stub
		User user = userDao.getFirstByUserId(userId);
		Role role = roleDao.getRoleById(roleId);
		if (user == null) {
			throw new Exception("指定的用户不存在");
		}
		if (role == null) {
			throw new Exception("指定的角色不存在");
		}
		return userRoleDao.saveUserRole(new UserAndRole(userId, roleId)) > 0;
	}

	@Override
	public List<UserRoleAndAuth> getUserRoleAndAuthorizeModules(Long id) throws Exception {
		if (id == null) {
			throw new Exception("ID为空");
		}
		return userDao.getAuthModuleAndRoleByUserId(id);
	}
	
	
	@Override
	public JSONObject getUserAccount() {
		try {
			LoginUser nowLoginUser = cache.getNowUser();
			User user = nowLoginUser.getUser();
			List<UserRoleAndAuth> userRoleAndAuths = getUserRoleAndAuthorizeModules(user.getId());
			JSONObject userAndRole = new JSONObject();
			userAndRole.put("id", user.getId());
			userAndRole.put("login", user.getUsername());
			userAndRole.put("firstName", "");
			userAndRole.put("lastName", "");
			userAndRole.put("email", user.getEmail());
			userAndRole.put("imageUrl", "");
			userAndRole.put("activated", true);
			userAndRole.put("langKey", "zh-cn");
			userAndRole.put("createdBy", user.getCreateBy());
			userAndRole.put("createdDate", user.getCreateTime());
			userAndRole.put("lastModifiedBy", "");
			userAndRole.put("lastModifiedDate", "");
			JSONArray array = new JSONArray();
			for (UserRoleAndAuth userRole : userRoleAndAuths) {
				if (!array.contains(userRole.getRoleName())) {
					array.add(userRole.getRoleName());
				}
			}
			userAndRole.put("authorities", array);
			return userAndRole;
		} catch (Exception e) {
			logger.info("[UserServiceImpl][updatePassword] e,", e);
		}
		return null;
	}

	@Override
	public void updateUser(User user) {
		// TODO Auto-generated method stub
		userDao.updateUser(user);
	}

	@Override
	public List<User> getAllUsers(String sortParam, long pageNum, long pageSize) throws Exception {
		logger.info("[ForkliftPlanServiceImpl][getAllUsers] sortParam:{},page:{},size:{}", sortParam, pageNum,
				pageSize);
		long allNum = userDao.count();
		long start = 0L;
		if (pageNum == 0 && pageSize == 0) {
			start = 0;
			pageSize = allNum;
		} else {
			start = (pageNum - 1) * pageSize;
			if (start > allNum) {
				throw new Exception("请求的页已经不存在");
			}
		}
		return userDao.findByPageAndOrderCondition(sortParam, start, pageSize);
	}
	
}
